package com.liaoyi.myble.adapter;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.liaoyi.myble.App;
import com.liaoyi.myble.R;
import com.liaoyi.myble.activity.ContentActivity;
import com.liaoyi.myble.data.Device;
import com.liaoyi.myble.service.BluetoothService;

import java.util.ArrayList;
import java.util.List;

public class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.ViewHolder> implements View.OnClickListener {

    private static final String TAG = "DeviceAdapter";
    private List<Device> devices = new ArrayList<>();

    public DeviceAdapter(List<Device> devices) {
        this.devices = devices;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.device_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        holder.deviceName.setText(devices.get(position).getName());
        holder.deviceMac.setText(devices.get(position).getMac());
        holder.layout.setOnClickListener(this);
    }

    @Override
    public int getItemCount() {
        return devices.size();
    }

    @Override
    public void onClick(View view) {
        BluetoothService bluetoothService = App.instance.bluetoothService;
        bluetoothService.stopScan();
        ContentActivity.actionStart(view.getContext(),((TextView) view.findViewById(R.id.device_mac)).getText().toString());
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        private TextView deviceName;
        private TextView deviceMac;
        private LinearLayout layout;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            deviceName = (TextView) itemView.findViewById(R.id.device_name);
            deviceMac = (TextView) itemView.findViewById(R.id.device_mac);
            layout = (LinearLayout) itemView.findViewById(R.id.item_layout);
        }
    }
}
